// js/pages/SettlementPage.js
import BasePage from './BasePage.js';
import TextRenderer from '../utils/TextRenderer.js';

// 提取常量
const UI_CONSTANTS = {
  COLORS: {
    TITLE_TEXT: '#505E91',
    AMOUNT_TEXT: '#FB6F6E',
    LABEL_TEXT: '#FFFFFF',
    VALUE_TEXT: '#C7BD91',
    BUTTON_TEXT: '#ffffff',
    SHAPE_BLUE: '#1e3a5f',
    SHAPE_DARK: '#1F203F'
  },
  SIZES: {
    BUTTON_WIDTH: 239,
    BUTTON_HEIGHT: 88,
    AMOUNT_HEIGHT: 94,
    DETAIL_HEIGHT: 50,
    DETAIL_SPACING: 70
  },
  POSITIONS: {
    BACK_BUTTON: { X: 78, Y: 28, WIDTH: 28, HEIGHT: 42 },
    TITLE: { Y: 30 },
    EARN_ICON: { X: 28, Y: 246, WIDTH: 338, HEIGHT: 286 },
    PROMPT_CARD: { X: 1320, Y: 150, WIDTH: 148, HEIGHT: 150 },
    AMOUNT_SHAPE: { X: null, Y: 158, WIDTH: 660, HEIGHT: 94, OFFSET: 25 },
    DETAIL_SHAPES: { X: 512, START_Y: 272, WIDTH: 648, HEIGHT: 50, OFFSET: 12, SPACING: 70 },
    BUTTONS: { Y: 588, TEXT_Y: 618 },
    SAVE_BUTTON: { X: 376, TEXT_X: 419 },
    SHARE_BUTTON: { X: 738, TEXT_X: 785 },
    AGAIN_BUTTON: { X: 1082, TEXT_X: 1125 }
  },
  FONT_SIZES: {
    TITLE: 52,
    AMOUNT: 60,
    LABEL: 28,
    BUTTON: 32
  },
  TOUCH_AREAS: {
    BACK_BUTTON: { X: 78, Y: 28, WIDTH: 46, HEIGHT: 28 },
    SAVE_BUTTON: { X: 370, Y: 580, WIDTH: 230, HEIGHT: 90 },
    SHARE_BUTTON: { X: 730, Y: 580, WIDTH: 220, HEIGHT: 90 },
    AGAIN_BUTTON: { X: 1080, Y: 580, WIDTH: 130, HEIGHT: 90 }
  }
};

export default class SettlementPage extends BasePage {
  constructor(canvas, ctx, pageManager, resourceManager, screenAdapter, api, userManager) {
    super(canvas, ctx, pageManager, resourceManager, screenAdapter);
    this.api = api;
    this.userManager = userManager;
    this.textRenderer = new TextRenderer(ctx, screenAdapter);

    // 页面状态
    this.pageState = {
      isInitialized: false,
      isSharing: false
    };

    // 游戏数据
    this.gameData = null;

    // 详细信息配置
    this.detailItems = [
      { label: '时间', key: 'begin_date', formatter: this.formatDate.bind(this) },
      { label: '股票', key: 'name' },
      { label: '个人涨幅', key: 'stock_increase', suffix: '%' },
      { label: '我的收益率', key: 'revenue_ratio', suffix: '%' }
    ];
  }

  onInit() {
    return Promise.resolve();
  }

  /**
   * 页面初始化方法
   */
  async initialize() {
    try {
      await this.initializeUI();
      await this.fetchGameData();
      this.pageState.isInitialized = true;
    } catch (error) {
      console.error('结算页面初始化失败:', error);
      throw error;
    }
  }

  /**
   * 初始化UI
   */
  async initializeUI() {
    // 预留UI初始化逻辑
  }

  /**
   * 获取游戏数据
   */
  async fetchGameData() {
    try {
      this.gameData = wx.getStorageSync('gameData');
      if (!this.gameData) {
        console.warn('未找到游戏数据');
        // 可以设置默认数据或返回上一页
      }
    } catch (error) {
      console.error('获取游戏数据失败:', error);
      throw error;
    }
  }

  /**
   * 渲染页面
   */
  render() {
    if (!this.pageState.isInitialized) return;

    this.renderBackground();
    this.renderHeader();
    this.renderIcons();
    this.renderCenterAmount();
    this.renderButtons();
  }

  /**
   * 渲染背景
   */
  renderBackground() {
    const recordBg = this.resourceManager.getImage('recordBg');
    if (recordBg) {
      this.ctx.drawImage(recordBg, 0, 0, this.screenAdapter.DESIGN_WIDTH, this.screenAdapter.DESIGN_HEIGHT);
    }
  }

  /**
   * 渲染顶部标题栏
   */
  renderHeader() {
    // 返回按钮
    const backIcon = this.resourceManager.getImage('backIcon');
    if (backIcon) {
      this.ctx.drawImage(backIcon, UI_CONSTANTS.POSITIONS.BACK_BUTTON.X, UI_CONSTANTS.POSITIONS.BACK_BUTTON.Y,
        UI_CONSTANTS.POSITIONS.BACK_BUTTON.WIDTH, UI_CONSTANTS.POSITIONS.BACK_BUTTON.HEIGHT);
    }

    // 标题
    this.textRenderer.drawText('战绩榜', this.screenAdapter.DESIGN_WIDTH / 2, UI_CONSTANTS.POSITIONS.TITLE.Y,
      `${UI_CONSTANTS.FONT_SIZES.TITLE}px ${this.textRenderer.systemFont}`,
      UI_CONSTANTS.COLORS.TITLE_TEXT, 'center', 'top');
  }

  /**
   * 渲染图标
   */
  renderIcons() {
    // 收益图标
    const earnIcon = this.resourceManager.getImage('earnIcon');
    if (earnIcon) {
      this.ctx.drawImage(earnIcon, UI_CONSTANTS.POSITIONS.EARN_ICON.X, UI_CONSTANTS.POSITIONS.EARN_ICON.Y,
        UI_CONSTANTS.POSITIONS.EARN_ICON.WIDTH, UI_CONSTANTS.POSITIONS.EARN_ICON.HEIGHT);
    }

    // 提示卡片
    const promptCard = this.resourceManager.getImage('promptCard');
    if (promptCard) {
      this.ctx.drawImage(promptCard, UI_CONSTANTS.POSITIONS.PROMPT_CARD.X, UI_CONSTANTS.POSITIONS.PROMPT_CARD.Y,
        UI_CONSTANTS.POSITIONS.PROMPT_CARD.WIDTH, UI_CONSTANTS.POSITIONS.PROMPT_CARD.HEIGHT);
    }
  }

  /**
   * 渲染中间收益金额区域
   */
  renderCenterAmount() {
    this.renderAmountShape();
    this.renderAmountText();
    this.renderDetailShapes();
    this.renderDetailItems();
  }

  /**
   * 渲染金额形状
   */
  renderAmountShape() {
    const { X, Y, WIDTH, HEIGHT, OFFSET } = UI_CONSTANTS.POSITIONS.AMOUNT_SHAPE;
    const centerX = this.screenAdapter.DESIGN_WIDTH / 2 - 300;

    this.drawShape(UI_CONSTANTS.COLORS.SHAPE_BLUE, WIDTH, HEIGHT, centerX, Y, OFFSET);
  }

  /**
   * 渲染金额文本
   */
  renderAmountText() {
    if (!this.gameData) return;

    const amount = this.formatAmount(this.gameData.revenue || 0);
    this.textRenderer.drawText(amount, this.screenAdapter.DESIGN_WIDTH / 2 + 30, 180,
      `bold ${UI_CONSTANTS.FONT_SIZES.AMOUNT}px ${this.textRenderer.systemFont}`,
      UI_CONSTANTS.COLORS.AMOUNT_TEXT, 'center', 'top');
  }

  /**
   * 渲染详细信息形状
   */
  renderDetailShapes() {
    const { X, START_Y, WIDTH, HEIGHT, OFFSET, SPACING } = UI_CONSTANTS.POSITIONS.DETAIL_SHAPES;

    for (let i = 0; i < 4; i++) {
      const y = START_Y + i * SPACING;
      this.drawShape(UI_CONSTANTS.COLORS.SHAPE_DARK, WIDTH, HEIGHT, X, y, OFFSET);
    }
  }

  /**
   * 渲染详细信息项
   */
  renderDetailItems() {
    if (!this.gameData) return;

    const { X, START_Y, SPACING } = UI_CONSTANTS.POSITIONS.DETAIL_SHAPES;
    const rightX = 550;

    this.detailItems.forEach((item, index) => {
      const y = START_Y + index * SPACING + 13; // 调整文本位置

      // 获取和格式化值
      let value = this.getDetailValue(item);

      // 渲染标签
      this.textRenderer.drawText(item.label, rightX - 10, y,
        `${UI_CONSTANTS.FONT_SIZES.LABEL}px ${this.textRenderer.systemFont}`,
        UI_CONSTANTS.COLORS.LABEL_TEXT, 'left', 'top');

      // 渲染值
      this.textRenderer.drawText(value, rightX + 580, y,
        `${UI_CONSTANTS.FONT_SIZES.LABEL}px ${this.textRenderer.systemFont}`,
        UI_CONSTANTS.COLORS.VALUE_TEXT, 'right', 'top');
    });
  }

  /**
   * 获取详细信息值
   */
  getDetailValue(item) {
    if (!this.gameData || !item.key) return '--';

    let value = this.gameData[item.key];

    if (item.formatter) {
      return item.formatter(value);
    }

    if (value !== undefined && value !== null) {
      return value + (item.suffix || '');
    }

    return '--';
  }

  /**
   * 格式化日期
   */
  formatDate(dateString) {
    if (!dateString) return '--';

    try {
      // 如果有结束日期，显示开始-结束日期
      if (this.gameData && this.gameData.end_date) {
        return `${dateString}-${this.gameData.end_date}`;
      }
      return dateString;
    } catch (error) {
      console.error('日期格式化失败:', error);
      return dateString;
    }
  }

  /**
   * 格式化金额
   */
  formatAmount(amount) {
    if (!amount || amount === 0) return '0.00';

    try {
      return parseFloat(amount).toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      });
    } catch (error) {
      console.error('金额格式化失败:', error);
      return amount.toString();
    }
  }

  /**
   * 渲染底部按钮
   */
  renderButtons() {
    this.renderButton(UI_CONSTANTS.POSITIONS.SAVE_BUTTON, 'buyIcon', '保存相册');
    this.renderButton(UI_CONSTANTS.POSITIONS.SHARE_BUTTON, 'showIcon', '炫耀一下');
    this.renderButton(UI_CONSTANTS.POSITIONS.AGAIN_BUTTON, 'againIcon', '再来一局');
  }

  /**
   * 渲染单个按钮
   */
  renderButton(position, imageKey, text) {
    // 按钮图标
    const buttonIcon = this.resourceManager.getImage(imageKey);
    if (buttonIcon) {
      this.ctx.drawImage(buttonIcon, position.X, UI_CONSTANTS.POSITIONS.BUTTONS.Y,
        UI_CONSTANTS.SIZES.BUTTON_WIDTH, UI_CONSTANTS.SIZES.BUTTON_HEIGHT);
    }

    // 按钮文本
    this.textRenderer.drawText(text, position.TEXT_X, UI_CONSTANTS.POSITIONS.BUTTONS.TEXT_Y,
      `${UI_CONSTANTS.FONT_SIZES.BUTTON}px ${this.textRenderer.systemFont}`,
      UI_CONSTANTS.COLORS.BUTTON_TEXT, 'left', 'top');
  }

  /**
   * 绘制不规则形状
   */
  drawShape(color, width, height, x, y, offset) {
    this.ctx.fillStyle = color;
    this.ctx.beginPath();
    this.ctx.moveTo(x + offset, y);
    this.ctx.lineTo(width + x + offset, y);
    this.ctx.lineTo(width + x, y + height);
    this.ctx.lineTo(x, y + height);
    this.ctx.closePath();
    this.ctx.fill();
  }

  /**
   * 处理触摸开始事件
   */
  handleTouchStart(event) {
    const touch = event.touches[0];
    const logicPoint = this.screenAdapter.screenToLogic(touch.clientX, touch.clientY);
    // 预留触摸开始处理逻辑
  }

  /**
   * 处理触摸结束事件
   */
  handleTouchEnd(event) {
    const touch = event.changedTouches[0];
    const logicPoint = this.screenAdapter.screenToLogic(touch.clientX, touch.clientY);

    // 处理按钮点击
    this.handleButtonClick(logicPoint);
  }

  /**
   * 处理触摸移动事件
   */
  handleTouchMove(event) {
    // 预留触摸移动处理逻辑
  }

  /**
   * 处理按钮点击
   */
  handleButtonClick(point) {
    // 返回按钮
    if (this.isAreaClicked(point, UI_CONSTANTS.TOUCH_AREAS.BACK_BUTTON)) {
      this.pageManager.showPage('home');
      return;
    }

    // 保存相册按钮
    if (this.isAreaClicked(point, UI_CONSTANTS.TOUCH_AREAS.SAVE_BUTTON)) {
      this.handleSaveToAlbum();
      return;
    }

    // 炫耀一下按钮
    if (this.isAreaClicked(point, UI_CONSTANTS.TOUCH_AREAS.SHARE_BUTTON)) {
      this.handleShareWithImage();
      return;
    }

    // 再来一局按钮
    if (this.isAreaClicked(point, UI_CONSTANTS.TOUCH_AREAS.AGAIN_BUTTON)) {
      this.pageManager.showPage('game');
      return;
    }
  }

  /**
   * 检查区域是否被点击
   */
  isAreaClicked(point, area) {
    return point.x >= area.X &&
      point.x <= area.X + area.WIDTH &&
      point.y >= area.Y &&
      point.y <= area.Y + area.HEIGHT;
  }

  /**
   * 处理保存到相册
   */
  handleSaveToAlbum() {
    if (this.pageState.isSharing) return;

    try {
      this.canvas.toTempFilePath({
        x: 0,
        y: 0,
        width: 1624,
        height: 750,
        destWidth: 1624,
        destHeight: 750,
        success: (res) => {
          wx.hideLoading();
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: () => {
              wx.showToast({
                title: '保存成功',
                icon: 'success'
              });
            },
            fail: (error) => {
              console.error('保存到相册失败:', error);
              wx.showToast({
                title: '保存失败',
                icon: 'error'
              });
            }
          });
        }
      })
    } catch (error) {
      console.error('保存到相册异常:', error);
      wx.showToast({
        title: '保存失败',
        icon: 'error'
      });
    }
  }

  /**
   * 处理分享图片
   */
  handleShareWithImage() {
    if (this.pageState.isSharing) return;

    this.pageState.isSharing = true;

    wx.showLoading({
      title: '正在生成分享图...',
    });

    try {
      this.canvas.toTempFilePath({
        x: 0,
        y: 0,
        width: 1624,
        height: 750,
        destWidth: 1624,
        destHeight: 750,
        success: (res) => {
          wx.hideLoading();
          wx.shareAppMessage({
            imageUrl: res.tempFilePath
          })
        }
      })
    } catch (error) {
      wx.hideLoading();
      this.pageState.isSharing = false;
      console.error('分享异常:', error);
      wx.showToast({
        title: '分享失败',
        icon: 'error'
      });
    }
  }
}
